import { ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { sendSMS } from '@/api/login'
import { LoginSMSRequestData } from '@/api/login/types/login'

interface FormState {
  form: LoginSMSRequestData
  isLoading: boolean
  rule: FormRules
  disable: boolean
}
export function useSMS(formState: FormState) {
  const sendSMSLabel = ref<string>('<span>获取验证码</span>')
  const Countdown = () => {
    let counter = 60
    formState.disable = true
    const intervalId = setInterval(() => {
      if (counter > 0) {
        sendSMSLabel.value = `<span><span style='color:#45aaff'>${counter}</span>秒后重试</span>`
        counter -= 1
      } else {
        sendSMSLabel.value = '<span>发送验证码</span>'
        formState.disable = false
        clearInterval(intervalId)
      }
    }, 1000)
  }

  const handleSendSMS = (formInstance: FormInstance | null) => {
    console.log(formInstance)

    if (formInstance) {
      formInstance.validateField('phoneNumber', (valid: boolean | string) => {
        if (valid === true) {
          sendSMS({
            phoneNumber: formState.form.phoneNumber,
            channel: 'Service',
          }).then((res) => {
            if (res.resultCode === 0) {
              ElMessage.success(res.resultMessage)
              Countdown()
            }
          })
        }
      })
    }
  }

  return {
    sendSMSLabel,
    handleSendSMS,
  }
}
